//用户openid
"use strict"
const dbase = require('../dbase');
class openid extends dbase.branch.mongodb {
    constructor(branch){
        super(branch,'openid');
    }
    //登录
    login(sdk,openid){
        let token = arguments[2]||'';
        let time = Date.now();
        let guid,query;
        let access = this.ObjectID();
        let update = {"$set":{"access":access,"token":token}};
        let option = {"upsert":true,"multi":false,"fields":{"_id":1,"guid":1, "gzone":1,bind:1} };
        update['$setOnInsert'] = {"time":time,"gzone":[] };

        if(arguments[3]){
            guid = arguments[3];
            query = {"_id":guid};
        }
        else {
            guid = this.ObjectID();
            query = {"sdk":sdk,"openid":openid};
            update['$setOnInsert']['_id'] = guid;
        }

        update['$setOnInsert']['guid'] = guid;

        return this.update(query,update,option).then(ret=>{

            if(!ret){
                return Promise.reject('login result empty');
            }
            if(!ret["guid"]){
                ret["guid"] = guid;  //兼容老账号
            }
            let data = { "guid":ret["guid"]||guid,"access":access,"gzone":ret["gzone"]||[]};
            if(ret.bind) {
                data.bind = ret.bind
            }
            if( ret["_id"] == ret["guid"]){
                return data;
            }
            else {
                return get_gzone_from_guid.call(this,ret["guid"],data);
            }
        });
    }
    check(sdk,openid){
        let option = {"multi":false,"fields":{"_id":1,"guid":1,"token":1} };
        let query = {"sdk":sdk,"openid":openid};
        return this.find(query,option).then(ret=>{
            if(!ret){
                return Promise.reject('login result empty');
            }
            let data = { "openid":openid,"guid":ret["guid"],"token":ret["token"]};
            return data;
        });
    }
    //退出登录
    logout(sdk,openid){
        let data = arguments[2]||{};
        let time = Date.now();
        data['logout'] = time;
        let query = {"openid":openid,"sdk":sdk};
        let update = {"$set":data};
        let option = {"upsert":false,"multi":false};
        return this.update(query,update,option);
    }
    //服务器端验证access是否有效
    verify(access){
        let sid = arguments[1]||0;
        let query = {"access":access};
        let option = {multi:false,fields:{"sdk":1,"guid":1,'openid':1,"token":1,"time":1,"gzone":1} };
        return this.find(query,option).then(ret=>{
            if(!ret){
                return Promise.reject('access_not_exist');
            }
            let data = {"guid":ret["guid"]||ret["_id"],"openid":ret["openid"],"token":ret["token"],"sdk":ret["sdk"]};
            if(sid){
                let gzone = ret['_id'] == ret['guid'] ? ret['gzone']||[] : null;
                set_gzone_from_guid.call(this,data["guid"],sid,gzone);
            }
            return data;
        });
    }
    
}

module.exports = function(branch){
    return new openid(branch);
}


function set_gzone_from_guid(guid,sid,gzone){
    Promise.resolve().then(()=>{
        if(gzone){
            return gzone;
        }else {
            return this.get(guid,'gzone')
        }
    }).then(gzone=>{
        gzone = gzone||[];
        let i = gzone.indexOf(sid);
        if(i===0){
            return ;
        }
        if(i>0){
            gzone.splice(i,1);
        }
        gzone.unshift(sid);
        return this.set(guid,"gzone",gzone);
    }).catch(err=>{
        console.log("set_gzone_from_guid",err)
    })
}

function get_gzone_from_guid(guid,data) {
    return this.get(guid,'gzone').then((ret)=>{
        if(ret){
            data['gzone'] = ret;
        }
        return data;
    })
}